package com.deer.wms.base.system.web.task;

import com.deer.wms.base.system.finalUtil.TaskInfoState;
import com.deer.wms.base.system.model.task.TaskInfo;
import com.deer.wms.base.system.model.task.TaskInfoCriteria;
import com.deer.wms.base.system.model.task.TaskInfoDto;
import com.deer.wms.base.system.model.task.TaskInfoHistoryDto;
import com.deer.wms.base.system.service.task.BillInTaskInfoService;
import com.deer.wms.base.system.service.task.ITaskInfoService;
import com.deer.wms.base.system.service.task.TaskInfoHistoryService;
import com.deer.wms.base.system.util.JedisServiceUtil;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.framework.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 移库任务
 * @author 申紫微
 * @version 1.0
 * @description
 * @data 2021-01-06 15:39:11
 */

@Controller
@Slf4j
@RequestMapping("/remove/taskInfo")
public class MoveTaskInfoController extends BaseController {

    private String prefix = "task";

    @Autowired
    private ITaskInfoService taskInfoService;
    @Autowired
    private BillInTaskInfoService billInTaskInfoService;
    @Autowired
    private TaskInfoHistoryService taskInfoHistoryService;
    @Autowired
    private JedisServiceUtil jedisServiceUtil;

    @RequiresPermissions("remove:task:view")
    @GetMapping("")
    public String moveTaskPage(){
        return prefix + "/taskInfoOfMove";
    }

    @RequiresPermissions("remove:taskHistory:view")
    @GetMapping("/historyList")
    public String moveTaskHistoryPage(){
        return prefix + "/taskInfoOfMoveHistory";
    }

    /**
     * 重新下发任务，此处的重新下发任务，由人为触发，触发之后，会重新分配货位
     * @author 申紫微
     * @date 16:08 2021/1/6
     * @params
     * @return  com.deer.wms.common.core.result.Result
     **/
    @PostMapping("reSendMoveTaskInfo")
    @ResponseBody
    public Result reSendMoveTaskInfo(int id){
        Result res = new Result();
        TaskInfo taskInfo = taskInfoService.selectTaskInfoById(id);
//        TaskInfo inTask = billInTaskInfoService.selectTaskInfoById(id);
        //String reHandleMoveTask = "reHandleMoveTask:"+ taskInfo.getRoadWay();
        //String reHandleInTask = "reHandleInTask:"+ taskInfo.getRoadWay();
        if (null != taskInfo){
            taskInfo.setState(TaskInfoState.STATE_ONT);
            int i = taskInfoService.updateTaskInfo(taskInfo);
            if (taskInfo.getType().equals(TaskInfoState.MOVE_TYPE)) {
                // 设置重新分配货位的KEY
                //String readyPutGoodsHaveGoods = "moveTaskPutGoodsHaveGoods:".concat(String.valueOf(taskInfo.getTaskNumber())).concat(taskInfo.getBoxCode());
                // 设置重新分配货位的次数的 KEY
                //String readyPutGoodsHaveGoodsCount = "moveTaskPutGoodsHaveGoodsCount:".concat(String.valueOf(taskInfo.getTaskNumber())).concat(taskInfo.getBoxCode());
                //清理掉重新分配货位的标志
                //jedisServiceUtil.clean(readyPutGoodsHaveGoods);
                //jedisServiceUtil.clean(readyPutGoodsHaveGoodsCount);
                //jedisServiceUtil.set(reHandleMoveTask, String.valueOf(taskInfo.getTaskNumber()));
            }
            if (i > 0){
                res = ResultGenerator.genSuccessResult();
            }else {
                res = ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR);
            }
        }
       /* if (null != inTask){
            taskInfo.setState(TaskInfoState.STATE_ONT);
            int i = billInTaskInfoService.updateTaskInfo(taskInfo);
            if(taskInfo.getType().equals(TaskInfoState.BILLIN_TYPE)){
                //如果是入库，一般人工找一个空货位放进去，然后强制完成，然后修改库存即可
                // 设置重新分配货位的次数的 KEY
                String readyPutGoodsHaveGoods = "inTaskPutGoodsHaveGoods:".concat(String.valueOf(taskInfo.getTaskNumber())).concat(taskInfo.getBoxCode());
                String readyPutGoodsHaveGoodsCount = "inTaskPutGoodsHaveGoodsCount:".concat(String.valueOf(taskInfo)).concat(taskInfo.getBoxCode());
                //清理掉重新分配货位的标志
                jedisServiceUtil.clean(readyPutGoodsHaveGoods);
                jedisServiceUtil.clean(readyPutGoodsHaveGoodsCount);
                jedisServiceUtil.set(reHandleInTask,String.valueOf(taskInfo.getTaskNumber()));
            }
            if (i > 0){
                res = ResultGenerator.genSuccessResult();
            }else {
                res = ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR);
            }
        }*/
        return res;
    }

    /*作业历史*/
    @PostMapping("/moveTaskfindList")
    @ResponseBody
    public TableDataInfo moveTaskfindList(TaskInfoDto taskInfoDto){
        startPage();
        List<TaskInfoDto> list = taskInfoService.findTaskWorkList(taskInfoDto);
        return getDataTable(list);
    }

    /**
     * 移库任务强制完成
     * @author 申紫微
     * @date 9:36 2021/1/7
     * @params id
     * @return com.deer.wms.common.core.result.Result
     **/
    @PostMapping("/moveTaskForceComplete")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result moveTaskForceComplete(int id){
        TaskInfo taskInfo = taskInfoService.selectTaskInfoById(id);
        if (null == taskInfo){
            return ResultGenerator.genFailResult(CommonCode.TASKINFO_OUTERROR,"任务不存在");
        }
        // 设置移库任务的状态为已经完成，并更新任务状态
        taskInfo.setState(TaskInfoState.STATE_THREE);
        String createUserName = ShiroUtils.getLoginName();
        taskInfo.setCreateUserName(createUserName);
        int i = taskInfoService.updateTaskInfo(taskInfo);
        //taskInfo.setTaskId(String.valueOf(taskInfo.getId()));
        // 保存移库历史任务
        int saveTaskHis=taskInfoHistoryService.saveTaskInfoHistory(taskInfo);
        boolean handleDBRes = taskInfoService.moveTaskForceComplete(id);
        int delRes = taskInfoService.deleteTaskInfoById(id);
        if (i > 0 && saveTaskHis > 0 && delRes > 0 && handleDBRes){
            return ResultGenerator.genSuccessResult();
        }else {
            log.error("移库任务强制完成失败,事务回滚");
            try {
                throw new Exception("移库任务强制完成失败,事务回滚，手动抛异常");
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                log.error(e.getMessage());
            }
            return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR);
        }
    }

    @PostMapping("/moveTaskHistoryList")
    @ResponseBody
    public TableDataInfo moveTaskHistoryList(TaskInfoCriteria taskInfoCriteria){
        startPage();
        List<TaskInfoHistoryDto> list = taskInfoHistoryService.moveTaskHistory(taskInfoCriteria);
        return getDataTable(list);
    }


}
